#!/usr/bin/env bash
set -eo pipefail
[[ $DOKKU_TRACE ]] && set -x
source "$PLUGIN_AVAILABLE_PATH/config/functions"

trigger-builder-herokuish-builder-build() {
  declare desc="builder-herokuish builder-build plugin trigger"
  declare trigger="builder-build"
  declare BUILDER_TYPE="$1" APP="$2" SOURCECODE_WORK_DIR="$3"

  if [[ "$BUILDER_TYPE" != "herokuish" ]]; then
    return
  fi

  local IMAGE=$(get_app_image_name "$APP")
  local DOKKU_APP_CACHE_DIR="$DOKKU_ROOT/$APP/cache"
  local DOKKU_APP_HOST_CACHE_DIR="$DOKKU_HOST_ROOT/$APP/cache"
  local DOCKER_COMMIT_LABEL_ARGS=("--change" "LABEL org.label-schema.schema-version=1.0" "--change" "LABEL org.label-schema.vendor=dokku" "--change" "LABEL com.dokku.app-name=$APP")
  local DOCKER_RUN_LABEL_ARGS="--label=com.dokku.app-name=$APP"
  local CID

  pushd "$SOURCECODE_WORK_DIR" &>/dev/null

  eval "$(config_export app "$APP")"

  DOKKU_IMAGE="$(config_get "$APP" DOKKU_IMAGE || echo "$DOKKU_IMAGE")"
  plugn trigger builder-create-dokku-image "$BUILDER_TYPE" "$APP" "$SOURCECODE_WORK_DIR" "$DOKKU_IMAGE"
  NEW_DOKKU_IMAGE=$(plugn trigger builder-dokku-image "$BUILDER_TYPE" "$APP" "$SOURCECODE_WORK_DIR" "$DOKKU_IMAGE")
  [[ -n "$NEW_DOKKU_IMAGE" ]] && DOKKU_IMAGE="$NEW_DOKKU_IMAGE"

  CID=$(tar -c . | "$DOCKER_BIN" container run "${DOCKER_RUN_LABEL_ARGS[@]}" $DOKKU_GLOBAL_RUN_ARGS -i -a stdin "$DOKKU_IMAGE" /bin/bash -c "mkdir -p /app && tar -xC /app")
  if test "$("$DOCKER_BIN" container wait "$CID")" -ne 0; then
    dokku_log_warn "Failure extracting app code"
    return 1
  fi

  "$DOCKER_BIN" container commit "${DOCKER_COMMIT_LABEL_ARGS[@]}" "$CID" "$IMAGE" >/dev/null
  [[ -d $DOKKU_APP_CACHE_DIR ]] || mkdir -p "$DOKKU_APP_CACHE_DIR"
  plugn trigger pre-build-buildpack "$APP" "$SOURCECODE_WORK_DIR"

  local DOCKER_ARGS=$(: | plugn trigger docker-args-build "$APP" "$BUILDER_TYPE")
  [[ "$DOKKU_TRACE" ]] && DOCKER_ARGS+=" -e TRACE=true "
  DOCKER_ARGS+=$(: | plugn trigger docker-args-process-build "$APP" "$BUILDER_TYPE")

  declare -a ARG_ARRAY
  eval "ARG_ARRAY=($DOCKER_ARGS)"

  local DOKKU_CONTAINER_EXIT_CODE=0
  local CID=$("$DOCKER_BIN" container create "${DOCKER_RUN_LABEL_ARGS[@]}" $DOKKU_GLOBAL_RUN_ARGS -v $DOKKU_APP_HOST_CACHE_DIR:/cache -e CACHE_PATH=/cache "${ARG_ARRAY[@]}" $IMAGE /build)
  plugn trigger post-container-create "app" "$CID" "$APP" "build"
  "$DOCKER_BIN" container start "$CID" >/dev/null || DOKKU_CONTAINER_EXIT_CODE=$?
  "$DOCKER_BIN" container attach "$CID"
  DOKKU_CONTAINER_EXIT_CODE="$("$DOCKER_BIN" container wait "$CID" 2>/dev/null || echo "$DOKKU_CONTAINER_EXIT_CODE")"

  if [[ "$DOKKU_CONTAINER_EXIT_CODE" -ne 0 ]]; then
    dokku_log_warn "Failure during app build"
    return 1
  fi

  "$DOCKER_BIN" container commit "${DOCKER_COMMIT_LABEL_ARGS[@]}" "$CID" "$IMAGE" >/dev/null

  plugn trigger post-build-buildpack "$APP" "$SOURCECODE_WORK_DIR"
}

trigger-builder-herokuish-builder-build "$@"
